package com.whfc.iot.mach.redis;

import com.whfc.common.util.JSONUtil;
import com.whfc.hdc.dto.AppDeviceCmdDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2021-07-22 11:43
 */
@Component
public class MachCmdRedisDao {

    private static final String DEVICE_CMD_KEY = "device-cmd-%s";

    private static final int EXPIRE_SECONDS = 2 * 60;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 设置硬件指令缓存
     *
     * @param cmd
     */
    public void setCmd(AppDeviceCmdDTO cmd) {
        String key = String.format(DEVICE_CMD_KEY, cmd.getDeviceId());
        String val = JSONUtil.toString(cmd);
        redisTemplate.opsForValue().set(key, val, EXPIRE_SECONDS, TimeUnit.SECONDS);
    }

    /**
     * 获取硬件指令缓存
     *
     * @param deviceId
     * @return
     */
    public AppDeviceCmdDTO getCmd(Integer deviceId) {
        String key = String.format(DEVICE_CMD_KEY, deviceId);
        String val = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(val)) {
            AppDeviceCmdDTO cmdDTO = JSONUtil.parseObject(val, AppDeviceCmdDTO.class);
            return cmdDTO;
        }
        return null;
    }

    /**
     * 删除指令缓存
     *
     * @param deviceId
     */
    public void delCmd(Integer deviceId) {
        String key = String.format(DEVICE_CMD_KEY, deviceId);
        redisTemplate.delete(key);
    }
}
